from datetime import datetime
from datetime import datetime
from sqlalchemy import Column, Integer, String, Text, JSON, DateTime
from app import db


class Document(db.Model):
    """文档模型，用于存储 RAG 系统中的文档"""
    
    # 表名
    __tablename__ = 'documents'
    
    # 字段定义
    id = Column(Integer, primary_key=True)
    title = Column(String(255), nullable=False)
    content = Column(Text, nullable=False)
    doc_metadata = Column(JSON, default={})
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def __init__(self, **kwargs):
        # 调用父类初始化
        super(Document, self).__init__(**kwargs)
        # 初始化不需要存储到数据库的属性
        self._temp_data = None
        self._processing_status = "pending"
        # 普通实例变量，可以随时读取和修改
        self.temporary_flag = False
    
    @property
    def summary(self):
        """计算属性，不需要存储到数据库"""
        return self.content[:100] + "..." if len(self.content) > 100 else self.content
    
    @property
    def processing_status(self):
        """受控属性，通过setter方法控制赋值"""
        return self._processing_status
    
    @processing_status.setter
    def processing_status(self, value):
        """设置状态属性，可以添加验证逻辑"""
        if value in ["pending", "processing", "completed", "failed"]:
            self._processing_status = value
        else:
            raise ValueError("Invalid processing status")
    
    @property
    def simple_flag(self):
        """只读属性示例，返回temporary_flag的值"""
        return self.temporary_flag
    
    def __repr__(self):
        return f'<Document {self.id}: {self.title}>'